package netty.protobuf;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

/**
 * @author 帅小伙
 * @date 2022/1/16
 * @description
 */
public class NettyServer {


    public static void main(String[] args) throws Exception {
        /*
        * 创建bossGroup  和worker
        * 1.创建两个线程组  bossGroup   和  workerGroup
        * 2.一个处理请求  一个处理业务
        * 3.都是无线循环的
        * 4两者 子线程的个数 = cpu核数*2
        * 5 工作线程 轮询
        * */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);


        try {
            //创建服务器端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();

            // 使用链式编程进行设置
            bootstrap.group(bossGroup, workerGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)   // 使用NioSOckerChannel
                    .option(ChannelOption.SO_BACKLOG, 128)  //设置线程连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {// 匿名
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            // 指定Instance
                            pipeline.addLast("protoDecoder",new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance()));
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("服务器准备好了");

            //绑定端口 同步  生成一个channelFuture对象
            ChannelFuture cf = bootstrap.bind(6668).sync();


            //给cf注册监听器
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(cf.isSuccess()){
                        System.out.println("监听端口成功");
                    }else{
                        System.out.println("监听端口失败");
                    }
                }
            });

            // 对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }finally {
            //优雅的关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
